package com.chitang.handler;

import com.chitang.pool.ChannelHandlePool;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author: wjs
 * @CreateTime: 2023-03-10 14:18
 */
@Slf4j
@Component
public class NettyWebsocketHandler extends SimpleChannelInboundHandler<Object> {


    private WebSocketServerHandshaker handshaker;

    /**
     * 客户端建立连接时触发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("+++++++++++有连接请求：{}==>{}+++++++++++", ctx.channel().id(), ctx.channel().remoteAddress());
    }

    /**
     * 客户端断开连接时触发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        closeChannel(channel);
    }

    /**
     * 接收到消息时触发
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *            belongs to
     * @param msg the message to handle
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        }
        if (msg instanceof WebSocketFrame) {
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
        super.channelRead(ctx, msg);
    }

    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        String userId = (String)ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        // 判断是否关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            log.info("receive client 'CLOSE' msg!!! client:[{}]",userId);
            return;
        }
        // 判断是否ping消息
        if (frame instanceof PingWebSocketFrame) {
            ByteBuf retain = frame.content().retain();
            log.info("receive client 'PING' msg!!! client:[{}]",userId);
            ctx.channel().writeAndFlush(
                    new PongWebSocketFrame(retain));
            return;
        }
        // 本例程仅支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            log.info("本例程仅支持文本消息，不支持二进制消息");
            throw new UnsupportedOperationException(String.format(
                    "%s frame types not supported", frame.getClass().getName()));
        }
        // 返回应答消息
        String request = ((TextWebSocketFrame) frame).text();
        log.info("receive client TextWebSocketFrame：[{}]" + request);
        TextWebSocketFrame tws = new TextWebSocketFrame(new Date().toString()
                + ctx.channel().id() + "：" + request);
        // 返回【谁发的发给谁】
        ctx.channel().writeAndFlush(tws);
    }

    /**
     * 处理惟一的一次http请求
     *
     * @param ctx
     * @param req
     */
    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
        // 如果HTTP解码失败，返回HTTP异常
        if (!req.decoderResult().isSuccess()
                || (!"websocket".equals(req.headers().get("Upgrade")))) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        // 获取url后置参数
        String uri = req.uri();
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri);
        Map<String, List<String>> parameters = queryStringDecoder.parameters();

        if (uri.contains("?")) {
            uri = uri.substring(0, uri.indexOf("?"));
        }
        // 构造握手响应返回，本机测试
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                "ws://" + req.headers().get(HttpHeaders.Names.HOST) + uri,
                null, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
        // 获取路径后面的参数
        if (parameters.containsKey("id")) {
            String userId = parameters.get("id").get(0);
            log.info("client id is:{}", userId);
            // 存储channel
            Channel channel = ctx.channel();
            channel.attr(AttributeKey.valueOf("userId")).set(userId);
            ChannelHandlePool.channelMap.put(userId, channel);
        }
    }

    private void sendHttpResponse(ChannelHandlerContext ctx,
                                  FullHttpRequest req, DefaultFullHttpResponse res) {
        // 返回应答给客户端
        if (res.getStatus().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
                    CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        // 如果是非Keep-Alive，关闭连接
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }


    /**
     * 心跳处理
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //判断evt是否是IdleStateEvent(用于触发用户事件，包含读空闲/写空闲/读写空闲)
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;

            String evenType = null;
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    evenType = "读空闲";
                    break;
                case WRITER_IDLE:
                    evenType = "写空闲";
                    break;
                case ALL_IDLE:
                    evenType = "读写空闲";
                    closeChannel(ctx.channel());
                    break;
            }
            String userId = ctx.channel().attr(AttributeKey.valueOf("userId")).toString();
            log.info("客户端：{}==>{}==>{} 超时事件发生：{}", userId, ctx.channel().id(), ctx.channel().remoteAddress().toString(), evenType);
        }
        super.userEventTriggered(ctx, evt);
    }

    /**
     * 关闭channel连接，并删除缓存信息
     *
     * @param channel
     */
    private void closeChannel(Channel channel) {
        // 取出之前设置的客户端唯一ID
        Object o = channel.attr(AttributeKey.valueOf("userId")).get();
        if (Optional.ofNullable(o).isPresent()) {
            String userId = o.toString();
            ChannelHandlePool.channelMap.remove(userId);
            log.info("客户端：{} 断开连接", userId);
        }
        channel.close();
    }

    /**
     * 出现异常时触发
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("netty服务发生异常：{}", cause.getMessage());
        closeChannel(ctx.channel());
//        super.exceptionCaught(ctx, cause);
    }

}
